package edu.cuit.avatar.service.impl;

import edu.cuit.avatar.entity.Book;
import edu.cuit.avatar.service.BookService;

import java.io.*;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 图书业务实现类————将图书保存进内存
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/15 15:28
 */
public class BookServiceImplInFile implements BookService {
    @Override
    public Integer save(Book book) {
        //1.生成id
        var id = generateId();
        book.setId(id);
        try(var raf = new RandomAccessFile("D:/avatar/book.txt", "rw")){
            raf.seek(raf.length());
            if(raf.length() > 0)
                raf.writeBytes("\r\n");
            raf.writeBytes(new String(book.toString().getBytes("utf-8"),"iso-8859-1"));
            return id;
        } catch (IOException e){
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public void removeById(Serializable id) {
        //如果每行长度一致的，可以使用两个指针来控制；长度不一致使用临时文件
        try(var input = new BufferedReader(new FileReader("D:/avatar/book.txt"));
            var output = new RandomAccessFile("temp.txt", "rw")){
            String line = null;
            //用于控制是否去掉最后多余的\r\n
            boolean needOverride = false;
            while((line = input.readLine()) != null){
                var bookId = Integer.valueOf(line.split("      ")[0]);
                if(id != bookId) {
                    output.writeBytes(new String(line.getBytes("utf-8"),"iso-8859-1"));
                    output.writeBytes("\r\n");
                    needOverride = true;
                }
            }
            if(needOverride)
                output.setLength(output.length() - "\r\n".length());
        }catch (IOException e){
            e.printStackTrace();
        }
        var originalFile = new File("D:/avatar/book.txt");
        var tempFile = new File("temp.txt");
        originalFile.delete();
        tempFile.renameTo(originalFile);
    }

    @Override
    public void updateById(Book book) {
        //如果每行长度一致的，可以使用两个指针来控制；长度不一致使用临时文件
        try(var input = new BufferedReader(new FileReader("D:/avatar/book.txt"));
            var output = new RandomAccessFile("temp.txt", "rw")){
            if(output.length() == 0) return;
            String line = null;
            while((line = input.readLine()) != null){
                var bookId = Integer.parseInt(line.split("      ")[0]);
                if(book.getId() == bookId)
                    line = book.toString();

                output.writeBytes(new String(line.getBytes("utf-8"),"iso-8859-1"));
                output.writeBytes("\r\n");
            }

            output.setLength(output.length() - "\r\n".length());

        }catch (IOException e){
            e.printStackTrace();
        }
        var originalFile = new File("D:/avatar/book.txt");
        var tempFile = new File("temp.txt");
        originalFile.delete();
        tempFile.renameTo(originalFile);
    }

    @Override
    public List<Book> findAll() {
        List<Book> books = new ArrayList<>();
        try(var input = new BufferedReader(new FileReader("D:/avatar/book.txt"))){
            String line = null;
            while((line = input.readLine()) != null){
                var info = line.split("      ");
                var book = new Book();
                book.setId(Integer.parseInt(info[0]));
                book.setTitle(info[1]);
                book.setAuthor(info[2]);
                book.setPrice(Integer.parseInt(info[3]));
                book.setPublisher(info[4]);
                books.add(book);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return books;
    }

    @Override
    public Book findById(Serializable id) {
        Book book = null;
        try(var input = new BufferedReader(new FileReader("D:/avatar/book.txt"))){
            String line = null;

            while((line = input.readLine()) != null){
                var info = line.split("      ");
                if(Integer.valueOf(info[0]) == id) {
                    book = new Book();
                    book.setId(Integer.parseInt(info[0]));
                    book.setTitle(info[1]);
                    book.setAuthor(info[2]);
                    book.setPrice(Integer.parseInt(info[3]));
                    book.setPublisher(info[4]);
                    break;
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return book;
    }

    //生成id
    private int generateId(){
        int id = 0;
        try(var raf = new RandomAccessFile("D:/avatar/book.txt", "r")){
            String line = null;
            while((line = raf.readLine()) != null){
                var info = line.split("      ");
                if(Integer.parseInt(info[0]) > id)
                    id = Integer.parseInt(info[0]);
            }
        } catch (IOException e){
            e.printStackTrace();
        }

        return id + 1;
    }
}
